Skip to content

Know the invariants and the negated condition after a loop without break - #552

Merged
CatarinaGamboa merged 2 commits into
mainfrom
feat/545-facts-after-loop
Nov 23, 2026
Merged

CatarinaGamboa merged 2 commits into
mainfrom
feat/545-facts-after-loop

Conversation

@CatarinaGamboa

@CatarinaGamboa CatarinaGamboa commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #551; review/merge after it.

Fixes #545

Part of the loop invariant inference plan (#542).

What and why

After a loop, the variables it changes were havocked again: only their declared refinements were known, so after int i = 0; while (i < n) i++; nothing said i >= n. Now, after a loop that can only exit at its head through its condition, the instances after the loop get the invariants inferred in #551 and the negated condition:

  • exitsAtHeadThroughCondition: a while, for or for-each loop (not a do-while), with no break whose target is the loop (labelled or not), and a condition that writes no variable.
  • InvariantCandidates.condition translates the condition when it is built of &&, ||, ! and comparisons (<, <=, >, >=, ==, !=) of the terms a candidate may mention (int literals, int locals and parameters, +, -, *); otherwise only the invariants are added.
  • LoopInvariants.afterLoop adds them to the post-loop instances (after the existing havoc), like the head facts.

Also (found by the Codex review): TryChecker starts a catch block from any value a variable had in the try block, including values recorded in loop-body checks that name join instances of a dropped check. The post-loop instance used to be true, which hid them; with facts after the loop they surfaced as Variable #i_11 could not be found (already the case on main for a refined variable). The variable is now unknown in the catch block when such a value is among them.

Soundness argument

  • The invariants hold at the loop head on every visit (Infer loop invariants for the int locals a loop changes (Houdini) #551), including the last one, where the condition is evaluated to false and the loop exits.
  • For while/for without break, the code after the loop is reached only from that point (a return, throw or labelled jump to an outer statement does not reach it), and the condition writes nothing, so the state after the loop is the head state where the condition was false: the invariants and the negated condition describe it.
  • A do-while exits after its body and condition, where the head invariants need not hold (do { i = i + 5; } while (i < 3); keeps i <= 3 at the head but exits with i == 5), so it is excluded. A condition with a side effect (while (i++ < 10)) exits in a state after the head, so it is excluded too.
  • The negated condition is built from the same Java expression with pure terms only, so it means what the condition meant at the exit.
  • Making a variable unknown in a catch block only removes facts.

Before / after

int i = 0; while (i < n) i++; atLeast(i, n); (@Refinement("_ <= i") int n): before Refinement Error (only i's declared refinement known), after Correct.
for (; i < 10; i++) { if (next()) continue; } ten(i); (_ == 10): before Refinement Error, after Correct (invariant i <= 10 and !(i < 10)).

Tests

  • CorrectLoopExitFacts (the first two fail on Infer loop invariants for the int locals a loop changes (Houdini) #551 alone): i >= n after counting up with while; i == 10 after a for whose body has a continue; a loop in a try with a catch (spurious Not Found Error without the TryChecker change).
  • ErrorLoopExitFacts: no negated condition after a loop with break; none after a do-while (the example above); none after a condition that increments (while (i++ < 10) exits with i == 11).
  • InvariantCandidatesTest.translatesConditionsOverTheSameTerms: !, ||, &&, ==, != translated; conditions with calls or a literal true not.

Full suite passes locally.

🤖 Generated with Claude Code

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 1

  1. False positive — a loop fact escapes a try/catch join with a missing instance. In CatchGuard.java, the guard makes the annotated call safe on every path that reaches it:

    int i = 0;
    try {
      while (i < 10) {
        if (fail) throw new RuntimeException();
        i++;
      }
    } catch (RuntimeException e) {}
    if (i != 10) return;
    ten(i); // ten requires _ == 10

    Observed: HEAD reports Not Found Error: Variable #i_11 could not be found at ten(i); the compiled previous PR reports Correct! Passed Verification. The same error occurs in CatchGuardCall.java, whose loop condition cannot be translated into a post-loop condition fact. This points to an inferred invariant added by afterLoop() retaining a reference to an instance unavailable after the catch join. Suggested fix: keep the referenced instance available through the join, or remove/project facts that refer to instances outside the joined context. Add an integration test for this program.

No false negative found. The branch compiled successfully. The other tested violation cases—including labelled control flow, for updates, condition side effects, for-each, a changing bound, and a loop that never runs—reported errors. The new condition translator has unit coverage, but the post-loop facts need integration coverage across try/catch joins.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex round 1: what was done

  1. Fixed (spurious Not Found Error). Cause: TryChecker starts a catch block from any value a variable had in the try block, and those recorded values include instances from loop-body checks that refer to join instances of a dropped check. Before this PR the post-loop instance had refinement true, which made the "any of" disjunction true and hid the dangling names; the same error already happens on main for a refined variable (@Refinement("_ >= 0") int i = 0; in Codex's CatchGuard gives Variable #i_11 could not be found on main). Fix: when the "any of" refinement names a value no longer in the context, the variable is unknown in the catch block (weaker, so sound). Test: CorrectLoopExitFacts.loopInTry (Codex's program). Codex's CatchGuardCall also passes now.

Pushed in 1099fa5 (also reuses LoopInvariants.condition in exitsAtHeadThroughCondition, from the clean-code audit).

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 2

No false negative found. The branch reported refinement errors for the reachable violations in ExitPaths.java, EdgeConditions.java, and TryCatchFix.java. These cover labelled jumps, nested switch breaks, exception paths, for updates, for-each, condition side effects, and nested loops. The valid try/catch case produced no error, confirming the reported fix without reproducing the old “Variable could not be found” diagnostic.

  1. Code quality — add regression tests for the catch merge’s error paths. In TryCatchFix.java, ten(i) can run with i == 0 in both catch and finally. The branch reported Refinement Error at lines 27 and 39; the guarded valid case at line 16 produced no diagnostic. Add these two violating cases alongside the existing valid case in CorrectLoopExitFacts.java so future changes to TryChecker.java preserve both behaviors.

mvn -q compile -pl liquidjava-verifier -am succeeded. No repository files were changed.

What was done

  1. Declined (extra error tests for the catch merge): an unguarded ten(i) after the catch fails with or without the TryChecker change, and also under the unsound alternative of dropping the dangling alternatives (the value before the try, i == 0, stays among them), so these tests would not guard anything; the lean-test rule applies.

No false negative in two rounds; the Codex loop for this PR ends here.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Clean-code review

Audit of this PR's own new code, clean-code-principles.

  • [core-dry] exitsAtHeadThroughCondition had its own way of getting a loop's condition, duplicating LoopInvariants.condition. Fixed in 1099fa5: it reuses LoopInvariants.condition.
  • [core-dry] InvariantCandidates.condition maps BinaryOperatorKind to RJ operators like OperationsChecker.getOperatorFromKind (private there). Declined: sharing it means opening up that method for a small switch; kept local, as in Add the candidate invariants of the int locals a loop changes #550.
  • [func-small] afterLoop is three lines; exitsAtHeadThroughCondition states its three conditions in its Javadoc. OK.
  • [doc-why-not-what] The TryChecker change has a comment saying why a dangling value makes the variable unknown. OK.

@CatarinaGamboa
CatarinaGamboa force-pushed the feat/544-houdini-loop-invariants branch from 800c30e to 3775ff5 Compare November 23, 2026 17:18
@CatarinaGamboa
CatarinaGamboa force-pushed the feat/545-facts-after-loop branch from 1099fa5 to 0d6cdd4 Compare November 23, 2026 17:18
@CatarinaGamboa
CatarinaGamboa force-pushed the feat/544-houdini-loop-invariants branch from 3775ff5 to cfc266a Compare November 23, 2026 17:30
@CatarinaGamboa
CatarinaGamboa force-pushed the feat/545-facts-after-loop branch from 0d6cdd4 to 2049b41 Compare November 23, 2026 17:30
@CatarinaGamboa
CatarinaGamboa changed the base branch from feat/544-houdini-loop-invariants to main November 23, 2026 18:23
CatarinaGamboa and others added 2 commits November 23, 2026 18:23
After a while or for loop that only exits at its head, through its
condition (no break leaves it and its condition writes no variable), the
instances after the loop now satisfy the inferred invariants and the
negated condition, when the condition is built of comparisons of the
terms a candidate may mention. A do-while exits after its body, where
the invariants of the head need not hold, so it keeps only the declared
refinements, as do loops with a break.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… known

A catch block starts from any value a variable had in the try block,
including values recorded inside a loop body, which may refer to
instances of a check of the body that was dropped. With facts after the
loop, those references were no longer hidden by an unknown alternative
and the check failed with "Variable could not be found" (already the case
on main for a refined variable). The variable is now unknown in the catch
block when such a value is among them.

Also reuse LoopInvariants.condition for the loop exit check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa
CatarinaGamboa force-pushed the feat/545-facts-after-loop branch from 2049b41 to 233721d Compare November 23, 2026 18:23
@CatarinaGamboa
CatarinaGamboa merged commit 84dd629 into main Nov 23, 2026
1 check passed
CatarinaGamboa added a commit that referenced this pull request Nov 24, 2026
…ath (#555)

Fixes #553

Part of the loop invariant inference plan (#542). Independent of #552
(based on main).

## What and why
When an error stopped the check of a loop body before a back edge, the
candidate invariants assumed at the head were never checked on the paths
after it, so they were never dropped, and the reported error showed them
as facts (#553: `found total@18#1 >= 0 && total@18#1 <= 0 && ...`).

The issue suggested dropping the candidates not proved at a back edge
reached, or all of them if none was reached. I tried that first, and it
is sound, but it moves errors onto lines that are correct: in
```java
for (int i = 0; i < 10; i++) { use(i); small(i); }   // use: _ >= 0, small: _ < 5
```
the error at `small(i)` stops every check, so all candidates are
dropped, and the error is then reported at `use(i)` as `found i < 10 but
expected i >= 0`. That is the #537 false alarm again, in any loop that
has another error, which is what study participants will write.

So this PR keeps checking the rest of the body instead:
1. When an error stops a check (`checkUntilFixpoint` catches it), the
top-level statement of the body where it stopped (recorded by a `scan`
override) is **skipped** in the next checks: the checker forgets what it
may change (`changedIn`, as for the loop itself) and declares the
variable it declares, if any.
2. Houdini goes on with the statement skipped, so the candidates are
checked at every back edge, on every path.
3. Once a check drops nothing, the body is checked once more **without
skipping** (`reporting`), and that check reports the error, with
candidates proved on every path.
4. If a statement cannot be skipped (it continues a loop outside it,
changes an object whose typestates the loop follows, or is a local
class), or the error is outside the body statements (condition, update),
all candidates are dropped instead, and the error is reported by a check
that assumes none. A loop with no candidates rethrows at once, as
before.

## Soundness argument
- An error is only reported from a check with no skipped statement, and
either no candidates, or candidates that a check dropped none of (a
fixpoint).
- Skipping a statement over-approximates what it does to the facts
candidates can talk about (int locals): every variable it may write gets
a fresh instance with only its declared refinement. So candidates proved
with it skipped hold for the real statement too, in executions where no
earlier check failed. The declared refinement is the usual "assume after
a failed check".
- A skipped statement must not hide a back edge: one with a `continue`
to this loop or an outer loop cannot be skipped. A `break`, `return` or
`throw` it hides only adds paths to check.
- Typestates: a statement that changes an object whose typestates the
loop follows cannot be skipped, so the head typestates are computed as
before.
- Termination: each stopped check either adds a new skipped statement
(finitely many) or drops all candidates; each report check that does not
stop either drops a candidate or ends the loop.

## Before / after (main → this PR)
| Program | main | this PR |
|---|---|---|
| #553 reproducer | `found total@16#1 >= 0 && total@16#1 <= 0 &&
total@16#1 <= 100 && ...` | `found total@16#1 < 100 && total ==
total@16#1 + #read_result` |
| `for (i = 0; i < 10; i++) { use(i); small(i); }` | error at
`small(i)`, `found i < 10 && i >= 0 && i <= 10` | same (the suggested
"drop all" moved it to `use(i)`) |
| `for (i...) { small(i); k = k - 1; use(k); }` | error at **`use(k)`**,
`found k@8 >= 0 && k@8 <= 0 && ...`. `small(i)` passed only because of
the false `i <= 0` | error at **`small(i)`**, `found i < 10 && i >= 0 &&
i <= 10` |
| `while (i < 10) { if (c()) { bad(i); i = -1; } i++; }` | `found i < 10
&& i >= 0 && i <= 0 && i <= 10` | `found i < 10` |
| `int x = bad(i);` in a `for` (declaration skipped) | `... i >= 0 && i
<= 0 ...` | `found i < 10 && i >= 0 && i <= 10` |
| error before `i = i - 5; continue;` (cannot be skipped) | `... i >= 0
&& i <= 0 ...` | `found i < 10` |

## Tests
- `ErrorLoopUnprovedInvariant` (new fixture, one method): an accumulator
with an error after `nonNeg(i)`.
- `TestCounterexamples.errorInLoopBodyShowsNoUnprovedInvariant`: Found
has no `<= 0`. Fails on main (`#total_2 >= 0 && #total_2 <= 0 && ...`).
- The fixture's `Expect` line also fails with the suggested "drop all"
fix, which reports `nonNeg(i)` (line 17).

Full suite passes locally. Study tasks (`verify-tasks.py`, 55 variants):
verdicts and messages identical to `verify-cur-redesign.json`.

## Timing
Correct programs do the same work as before. A loop whose body has an
error now costs one more body check per skipped statement, plus the
report check. Same machine (shared, load ~5 on 4 cores, so noisy):

| | main | this PR |
|---|---|---|
| `mvn -q test` wall | 141 s | 144 s / 171 s (two runs) |
| Loop fixtures, cold SMT cache, median of 5 (ms) | | |
| `ErrorLoopInvariants` | 329 | 469 |
| `ErrorLoopCondition` | 470 | 606 |
| `ErrorLoopStateFixpoint` | 534 | 1175 |
| `CorrectLoopInvariants` | 599 | 603 |
| `CorrectLoopStateFixpoint` | 1115 | 1096 |
| Study tasks (`verify-tasks.py`, wall) | — | 233 s / 283 s |

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Invariant inference 3/6: invariant and negated condition after a loop without break

1 participant